<template>
  <div class="app-container app-content">
    <el-row class="line-bottom" v-show="showSearch">
      <el-col class="form_col">
        <el-form :model="queryParams" ref="queryForm" :size="formItemSize" v-show="showSearch"
                 :label-width="labelWidth">
          <div id="searchFilter" style="display: flex; flex-wrap: wrap;">
            <el-form-item label="区域名称" prop="sheetsName">
              <el-input :size="formItemSize"
                        v-model="queryParams.sheetsName"
                        placeholder="请输入区域名称"
                        clearable
                        @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="区域编号" prop="sheetsCode">
              <el-input :size="formItemSize"
                        v-model="queryParams.sheetsCode"
                        placeholder="请输入区域编号"
                        clearable
                        @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="详细地址" prop="sheetsAddr">
              <el-input :size="formItemSize"
                        v-model="queryParams.sheetsAddr"
                        placeholder="请输入详细地址"
                        clearable
                        @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="区域描述" prop="details">
              <el-input :size="formItemSize"
                        v-model="queryParams.details"
                        placeholder="请输入区域描述"
                        clearable
                        @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </div>
        </el-form>
      </el-col>

      <el-col class="form_query">
        <el-button v-show="collapseAble" type="text" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
        </el-button>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-col>
    </el-row>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['basedata:meterSheets:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="6">
        <el-alert
          title="每新增一个水司客户，需要新建该客户专用的通用区域！"
          type="warning"
          :closable="false">
        </el-alert>
      </el-col>

      <RightDropdown :columns="columns" :showSearch.sync="showSearch" @queryTable="getList"
                     @export="handleExport"></RightDropdown>
    </el-row>

    <el-table v-loading="loading" :data="sheetsList" size="mini" row-key="id" border :height="getAvailableHeight"
              default-expand-all :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column label="区域名称" align="left" prop="sheetsName" v-if="columns[0].visible" :show-overflow-tooltip="true"/>
      <el-table-column label="区域主键" align="left" prop="id" v-if="columns[6].visible"/>
      <el-table-column label="区域编号" align="left" prop="sheetsCode" width="200" v-if="columns[1].visible"/>
      <el-table-column label="区域类型" align="left" prop="deviceType" v-if="columns[2].visible">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.device_type" :value="scope.row.deviceType"/>
        </template>
      </el-table-column>
      <el-table-column label="经度" align="left" prop="lng" v-if="columns[8].visible"/>
      <el-table-column label="纬度" align="left" prop="lat" v-if="columns[9].visible"/>
      <el-table-column label="详细地址" align="left" prop="sheetsAddr" v-if="columns[3].visible"/>
      <el-table-column label="区域描述" align="left" prop="details" v-if="columns[4].visible"/>
      <el-table-column label="所属客户" align="left" prop="deptName" v-if="columns[7].visible">
<!--        <template slot-scope="scope">-->
<!--          <dict-tag :options="deptOption" :value="scope.row.tenantId"/>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" v-if="columns[5].visible"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-tooltip effect="dark" content="添加下级" placement="top">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-plus"
                @click="handleAdd(scope.row)"
                v-hasPermi="['basedata:meterSheets:add']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="修改" placement="top">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="scope.row.parentId !== 0"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['basedata:meterSheets:edit']"
            >
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="删除" placement="top">
            <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['basedata:meterSheets:remove']"
            >
            </el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

<!--    <pagination-->
<!--        v-show="total>0"-->
<!--        :total="total"-->
<!--        :page.sync="queryParams.pageNum"-->
<!--        :limit.sync="queryParams.pageSize"-->
<!--        @pagination="getList"-->
<!--    />-->

    <!-- 添加或修改区域管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="父级区域" prop="parentId" v-if="title === '添加区域管理'">
          <treeselect v-model="form.parentId" :options="parentMeterSheetsOptions" :normalizer="normalizer"
                      placeholder="请选择父级区域"/>
        </el-form-item>
        <el-form-item label="区域名称" prop="sheetsName">
          <el-input v-model="form.sheetsName" placeholder="请输入区域名称"/>
        </el-form-item>
<!--        <el-form-item label="区域类型" prop="deviceType">-->
<!--          <el-select v-model="form.deviceType" placeholder="请选择区域类型" style="width: 100%" :disabled="disabledDeviceType" v-show="systemID === 1">-->
<!--            <el-option v-for="dict in dict.type.sheets_metered" :key="dict.value" :label="dict.label"-->
<!--                       :value="parseInt(dict.value)"></el-option>-->
<!--          </el-select>-->
<!--          <el-select v-model="form.deviceType" placeholder="请选择区域类型" style="width: 100%" :disabled="disabledDeviceType" v-show="systemID === 2">-->
<!--            <el-option v-for="dict in dict.type.sheets_terminal" :key="dict.value" :label="dict.label"-->
<!--                       :value="parseInt(dict.value)"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="区域类型" prop="deviceType" v-if="title === '添加区域管理'">
          <el-select v-model="form.deviceType" placeholder="请选择区域类型" style="width: 100%" :disabled="disabledDeviceType" v-show="systemID === 2" @change="handleDeptChange">
            <el-option v-for="dict in dict.type.sheets_terminal" :key="dict.value" :label="dict.label"
                       :value="parseInt(dict.value)"></el-option>
          </el-select>
          <el-select v-model="form.deviceType" placeholder="请选择区域类型" style="width: 100%" :disabled="disabledDeviceType" v-show="systemID === 1" @change="handleDeptChange">
            <el-option v-for="dict in dict.type.sheets_metered" :key="dict.value" :label="dict.label"
                       :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属客户" prop="tenantId" v-show="currentSheetsType === 1 && title === '添加区域管理'" :rules="currentSheetsType === 1 ? {required: true ,message:'请选择区域',trigger: 'change'} : {required: false ,message:'请选择区域',trigger: 'change'}">
          <el-select filterable v-model="form.tenantId" placeholder="请选择所属客户" style="width: 100%" >
            <el-option
              v-for="dept in deptOption"
              :key="dept.tenantId"
              :label="dept.deptName"
              :value="dept.tenantId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="经度" prop="lng">
          <el-input v-model="form.lng" placeholder="请输入经度"/>
        </el-form-item>
        <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.lat" placeholder="请输入纬度"/>
        </el-form-item>
        <el-form-item label="详细地址" prop="sheetsAddr">
          <el-input v-model="form.sheetsAddr" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="区域描述" prop="details">
          <el-input v-model="form.details" placeholder="请输入区域描述"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deptList } from '@/api/system/dept.js'
import {getAreaTree} from "@/api/tree/index"
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {
  listMeterSheetsTree,
  getMeterSheets,
  delMeterSheets,
  addMeterSheets,
  updateMeterSheets
} from "@/api/basedata/meterSheets";
import { getSheetsTree } from "../../../api/tree";
import {mapState} from "vuex";

export default {
  name: "Sheets",
  components: {Treeselect},
  dicts: ['sheets_metered','sheets_terminal','device_type'],
  data() {
    return {
      // showDeptFormItem: false,
      // 当前选择的区域类型
      currentSheetsType: null,
      // 所属客户
      deptOption: [],
      disabledDeviceType: false,
      screenHeight: null,
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 区域管理表格数据
      sheetsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        sheetsName: null,
        sheetsCode: null,
        sheetsAddr: null,
        treeType: null,
        details: null,
      },
      // 列信息
      columns: [
        {key: 1, label: `区域名称`, visible: true, dataindex: 'sheetsName'},
        {key: 2, label: `区域编号`, visible: true, dataindex: 'sheetsCode'},
        {key: 3, label: `区域类型`, visible: true, dataindex: 'deviceType'},
        {key: 4, label: `详细地址`, visible: true, dataindex: 'sheetsAddr'},
        {key: 5, label: `区域描述`, visible: true, dataindex: 'details'},
        {key: 6, label: `备注`, visible: true, dataindex: 'remark'},
        {key: 7, label: `区域主键`, visible: true, dataindex: 'id'},
        {key: 8, label: `所属客户`, visible: true, dataindex: 'deptName'},
        {key: 9, label: `经度`, visible: true, dataindex: 'lng'},
        {key: 10, label: `纬度`, visible: true, dataindex: 'lat'},
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          {required: true, message: "请选中父级区域", trigger: "blur"}
        ],
        sheetsName: [
          {required: true, message: "区域名称不能为空", trigger: "blur"}
        ],
        deviceType: [
          {required: true, message: "区域类型不能为空", trigger: "blur"}
        ],
      },
      parentMeterSheetsOptions: [],
      maxShow: 4,
      formItemSize: 'mini',
      collapseAble: false,
      fold: false,
      labelWidth: '80px'
    };
  },
  watch: {
    systemID(val) {
      this.getList()
    }
  },
  created() {
    this.getList();
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    ...mapState({
      systemID: state => state.permission.systemID,
    }),
    // systemID() {
    //   return this.$store.state.permission.systemID
    // },
    getAvailableHeight() {
      return this.screenHeight - (this.showSearch ? 200 : 155)
    },
  },
  methods: {
    // 所属区域类型选择框change事件
    handleDeptChange(val) {
      this.currentSheetsType = val
    },
    // 获取所有客户
    getDeptList() {
      deptList().then(response => {
        this.deptOption = response.data
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.sheetsName,
        children: node.children
      };
    },
    /** 查询区域管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.treeType = "0," + this.systemID
      getSheetsTree(this.queryParams).then(response => {
        if(response.data){
          this.sheetsList = response.data;
          this.parentMeterSheetsOptions = JSON.parse(JSON.stringify(response.data));
        }
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        parentId: null,
        deviceType: null,
        tenantId: null,
        sheetsName: null,
        sheetsCode: null,
        details: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.currentSheetsType = null
      this.disabledDeviceType = false
      if (row) {
        this.form.parentId = row.id
      }
      this.open = true;
      this.title = "添加区域管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      debugger
      const id = row.id
      const currentRow = row
      // this.showDeptFormItem = false
      getMeterSheets(id).then(response => {
        this.form = response.data;
        // this.form.parentId = (response.data.parentId === 'root' ? undefined : response.data.parentId)
        this.open = true;
        this.title = "修改区域管理";
        if (currentRow.children == null || currentRow.children.length === 0){
          this.disabledDeviceType = false
        }else{
          this.disabledDeviceType = true
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      // const level = this.findDataLevel(this.form.parentId, this.parentMeterSheetsOptions);
      // if(level >3){
      //   this.$message.error("最多只能添加3级子节点");
      //   return
      // }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMeterSheets(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.getList();
              this.open = false;
              this.getTerminalTreeList();
              this.getMeteredTreeList();
            });
          } else {
            // this.parentMeterSheetsOptions.filter((item) => {
            //   const deviceType = this.getMeters(item, this.form)
            //   if(deviceType === 1){
            //     return this.$modal.msgWarning("户表区域下不可新建区域");
            //   }
            // })
            const deviceType = this.findDeviceType(this.parentMeterSheetsOptions, this.form.parentId)
            if(deviceType === 1){
              return this.$modal.msgWarning("户表区域下不可新建区域")
            }
            addMeterSheets(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.getList();
              this.open = false;
              this.getTerminalTreeList();
              this.getMeteredTreeList();
            });
          }
        }
      });
    },
    // 获取大用户区域树
    getTerminalTreeList() {
      let treeType = "0,2"
      getAreaTree(treeType).then(response => {
        localStorage.setItem('terminalTreeData', JSON.stringify(response.data))
      });
    },
    // 获取户表区域树
    getMeteredTreeList() {
      let treeType = "0,1"
      getAreaTree(treeType).then(response => {
        localStorage.setItem('meteredTreeData',JSON.stringify(response.data))
      });
    },
    // 判断父级区域是哪种类型
    findDeviceType(data, parentId){
      let res_deviceType = ''
      for(let i = 0; i < data.length; i++){
        if(data[i].id === parentId){
          res_deviceType = data[i].deviceType;
          break;
        }
        if(data[i].children && data[i].children.length > 0){
          const text = this.findDeviceType(data[i].children, parentId)
          if(text){
            return text;
          }
        }
      }
      return res_deviceType
    },
    // findDataLevel(id, list, level = 1){
    //   for(const item of list){
    //     if(item.parentId === id){
    //       return level
    //     }
    //     if(item.children && item.children.length > 0){
    //       return this.findDataLevel(id, item.children,level + 1)
    //     }
    //   }
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.id
      this.$modal.confirm('是否确认删除所选记录？').then(function () {
        return delMeterSheets(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basedata/meterSheets/export', {
        ...this.queryParams
      }, `区域信息.xlsx`)
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.formItemSize}`)
      const len = group?.length ? group?.length : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    }
  },
  mounted() {
    this.getDeptList();
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
};
</script>
<style scoped>
::v-deep .el-alert {
  padding: 5px 16px;
}
::v-deep .el-dialog__body{
  padding: 10px 30px;
}
.form_col {
  width: 80%;

  ::v-deep .el-form {
    width: 100%;
  }

  ::v-deep .el-form-item {
    width: 20%;
  }
}

.form_query {
  width: 20%;
  text-align: right;
}
</style>
